import { connection } from '../app/database/mysql';
import { noticeModal } from './notification.model';

/**
 * 获取内容
 */
export const getNotification = async (status: number) => {
  // 准备查询
  let statement = `
    SELECT SQL_CALC_FOUND_ROWS * FROM notice
  `;
  let where = []
  if (status >= 0) {
    where.push(`status = ` + status)
  }
  if (where.length > 0) {
    statement += ` where `
    for (let i = 0; i < where.length; i++) {
      statement += where[i]
      if (i < where.length - 1) {
        statement += ` and `
      }
    }
  }

  statement += ` ORDER by id DESC `

  // 执行查询
  const [data] = await connection.promise().query(statement)

  let totalStatement = `SELECT COUNT(id) as total FROM notice`
  const [result] = await connection.promise().query(totalStatement)
  let totalCount = result[0].total

  let res = {
    data,
    totalCount
  }
  // 提供数据
  return res;
}

/**
 * 按 ID 获取内容
 */
export const getIdNotification = async (postId: number) => {
  // 准备查询
  const statement = `
    SELECT * FROM notification
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, postId);
  let notification = data[0] as any

  // 提供数据
  return notification;
}

/**
 * 创建内容
 */
export const createNotice = async (post: noticeModal) => {
  // 准备查询
  const statement = `
    INSERT INTO notice
    SET ?
  `;
  
  // 执行查询
  const [data] = await connection.promise().query(statement, post);
  
  // 提供数据
  return data;
}

/**
 * 阅读内容
 */
export const readNotification = async (read: number, notification_id: number, user_id: number) => {
  // 准备查询
  const statement = `
    UPDATE user_notice
    SET \`read\` = ?
    WHERE notification_id = ? AND user_id = ?
  `;
  
  // 执行查询
  const [data] = await connection.promise().query(statement, [read,notification_id, user_id]);

  // 提供数据
  return data;
}

/**
 * 更新内容
 */
export const updateNotice = async (post: noticeModal, postId: number) => {
  // 准备查询
  const statement = `
    UPDATE notice
    SET ?
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, [post, postId]);

  // 提供数据
  return data;
}

/**
 * 删除内容
 */
export const deleteNotice = async (postId: number) => {
  // 准备查询
  const statement = `
    DELETE FROM notice
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, postId);

  // 提供数据
  return data;
}

/**
 * 状态
 */
export const noticeStatusChange = async (postId: number, post: any) => {
  // 准备数据
  const statement = `
    UPDATE notice
      SET ?
      WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, [post, postId]);

  // 提供数据
  return data;
};